package com.yifeng.repo.micro.service.server.auth.ucs.interceptor;

import com.gomcarter.frameworks.base.json.ErrorCode;
import com.yifeng.repo.micro.service.server.auth.ucs.interceptor.cache.UcsCache;
import com.yifeng.repo.micro.service.server.auth.ucs.interceptor.context.UcsContext;
import com.yifeng.repo.micro.service.server.auth.ucs.interceptor.excepiton.UcsLoginException;
import com.yifeng.repo.micro.service.server.auth.ucs.interceptor.model.UcsLoginUserInfo;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;

/**
 * 用户中心鉴权拦截器
 * @author zyh @2022.09.18
 */
@Order(HIGHEST_PRECEDENCE)
public class UcsAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        UcsLoginUserInfo ucsLoginUserInfo = UcsCache.get();
        if (ucsLoginUserInfo == null) {
            throw new UcsLoginException(ErrorCode.noLogin.getCode(), "鉴权失败");
        }
        UcsContext.set(ucsLoginUserInfo);
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        UcsContext.clear();
    }
}
